import Icon from '@ant-design/icons';
import { Tooltip } from 'antd';
import mapboxgl, { type Anchor } from 'mapbox-gl';
import type React from 'react';
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import type Mapless from '../../Mapless';
import ErrorBoundary from '../ErrorBoundary';
import DraggableMarkerGroup from './Group';
import styles from './index.module.less';
import markerSvg from './marker.svg?react';

// 定义 MapboxMarker 组件的 props 类型
type DraggableMarkerProps = {
  mapless?: Mapless | undefined;
  lngLat: mapboxgl.LngLat;
  children: React.ReactNode;
  className?: string;
  anchor?: Anchor;
};

const DraggableMarker = ({
  mapless,
  lngLat,
  children,
  className,
  anchor,
}: DraggableMarkerProps) => {
  const markerRef = useRef<mapboxgl.Marker>(undefined);
  const markerNodeRef = useRef(document.createElement('div'));
  const popupNodeRef = useRef(document.createElement('div'));

  const [position, setPosition] = useState<mapboxgl.LngLat>(lngLat);

  useEffect(() => {
    const { map } = mapless || {};
    if (!map) return;
    markerRef.current?.remove();
    markerRef.current = new mapboxgl.Marker({
      element: markerNodeRef.current,
      className: `${styles['react-marker']} ${className}`,
      anchor: anchor || 'center',
      draggable: true,
    })
      .setLngLat(lngLat)
      .addTo(map);
    markerRef.current.setPopup(
      new mapboxgl.Popup({
        closeOnMove: false,
        closeOnClick: false,
        className: styles['react-popup'],
        focusAfterOpen: false,
        anchor: 'top',
      })
        .setLngLat(lngLat)
        .setDOMContent(popupNodeRef.current),
    );
    markerRef.current.on('dragend', () => {
      setPosition(markerRef.current?.getLngLat() || lngLat);
    });
  }, [mapless, JSON.stringify(lngLat)]);

  useEffect(() => {
    return () => {
      markerRef.current?.remove();
      markerRef.current = undefined;
    };
  }, []);

  return (
    <>
      <ErrorBoundary message="DraggableMarker 1">
        {createPortal(
          <Tooltip
            title={
              <div style={{ fontSize: 10 }}>
                <div style={{ width: '100%', lineHeight: '12px' }}>
                  经度：{position.lng.toFixed(6)}
                </div>
                <div
                  style={{ width: '100%', lineHeight: '12px', marginBottom: 4 }}
                >
                  纬度：{position.lat.toFixed(6)}
                </div>
              </div>
            }
          >
            <Icon component={markerSvg} className={styles.icon} />
          </Tooltip>,
          markerNodeRef.current,
        )}
      </ErrorBoundary>
      <ErrorBoundary message="DraggableMarker 2">
        {createPortal(
          <div className={styles.content}>
            <div style={{ width: '100%', lineHeight: '12px' }}>
              经度：{position.lng.toFixed(6)}
            </div>
            <div style={{ width: '100%', lineHeight: '12px', marginBottom: 4 }}>
              纬度：{position.lat.toFixed(6)}
            </div>
            {children}
          </div>,
          popupNodeRef.current,
        )}
      </ErrorBoundary>
    </>
  );
};

DraggableMarker.Group = DraggableMarkerGroup;

export default DraggableMarker;
